<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="24" :xs="24">
        <el-form
          v-show="showSearch"
          ref="queryForm"
          :model="queryParams"
          :inline="true"
          label-width="68px"
        >
          <el-form-item label="疾病名字" prop="name">
            <el-input
              v-model="queryParams.name"
              placeholder="疾病名字"
              clearable
              size="small"
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
            >搜索</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              v-hasPermission="['knowledge:diseabled:add']"
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              v-hasPermission="['knowledge:diseabled:delete']"
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              @click="handleDelete"
            >删除</el-button>
          </el-col>
          <el-col :span="3">
            <el-button
              v-hasPermission="['knowledge:diseabled:updateCache']"
              type="success"
              plain
              icon="el-icon-refresh"
              size="mini"
              @click="handleUpdateCachedisabled"
            >更新缓存</el-button>
          </el-col>
        </el-row>

        <el-table v-loading="loading" :data="disabledList" style="width: 100%" empty-text="暂无数据" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column v-if="false" prop="id" label="序号" align="center" />
          <el-table-column prop="name" label="病名" align="center">
            <template slot-scope="scope">
              <el-popover
                trigger="hover"
                placement="top"
                width="400"
                :title="scope.row.name"
                :content="scope.row.desc"
              >
                <div slot="reference" class="name-wrapper">
                  <el-tag size="medium" type="warning">{{ scope.row.name }}</el-tag>
                </div>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column prop="easyGet" label="易感人群" align="center" show-overflow-tooltip />
          <el-table-column prop="getProb" label="得病概率" align="center" show-overflow-tooltip />
          <el-table-column prop="cureWay" label="治疗方法" align="center" show-overflow-tooltip />
          <el-table-column prop="curedProb" label="治愈概率" align="center" show-overflow-tooltip />
          <el-table-column prop="cureLasttime" label="治愈时间" align="center" show-overflow-tooltip />
          <el-table-column prop="cureDepartment" label="治疗科室" align="center" show-overflow-tooltip />
          <el-table-column
            label="操作"
            align="center"
            width="300"
          >
            <template v-if="scope.row.id !== 1" slot-scope="scope">
              <el-button
                v-hasPermission="['knowledge:diseabled:detail']"
                size="mini"
                type="success"
                icon="el-icon-more"
                @click="handleDetail(scope.row)"
              >详情</el-button>
              <el-button
                v-hasPermission="['knowledge:diseabled:update']"
                size="mini"
                type="primary"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
              >修改</el-button>
              <el-button
                v-hasPermission="['knowledge:diseabled:delete']"
                size="mini"
                type="danger"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <el-pagination
      :page-size.sync="queryParams.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      :page-sizes="[10, 20, 30, 40]"
      :current-page.sync="queryParams.pageNum"
      @current-change="getList"
      @size-change="getList"
    />
    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="65%" append-to-body top="0vh">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="病名" prop="name">
              <el-input
                v-model="form.name"
                placeholder="请输入疾病名字"
                maxlength="32"
                :readonly="detailOpen"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属科室" prop="cureDepartment">
              <el-input
                v-model="form.cureDepartment"
                placeholder="请输入科室名字"
                maxlength="32"
                :readonly="detailOpen"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="治愈时间" prop="cureLasttime">
              <el-input
                v-model="form.cureLasttime"
                placeholder="请输入至少治愈时间"
                maxlength="32"
                :readonly="detailOpen"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="治疗方式" prop="cureWay">
              <el-input
                v-model="form.cureWay"
                placeholder="请输入治疗方式"
                maxlength="124"
                :readonly="detailOpen"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="治愈概率" prop="curedProb">
              <el-input
                v-model="form.curedProb"
                placeholder="请输入治愈概率"
                maxlength="16"
                :readonly="detailOpen"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="易感人群" prop="easyGet">
              <el-input
                v-model="form.easyGet"
                placeholder="请输入易感人群"
                maxlength="32"
                :readonly="detailOpen"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="得病概率" prop="getProb">
              <el-input
                v-model="form.getProb"
                placeholder="请输入得病概率"
                maxlength="16"
                :readonly="detailOpen"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item
              label="疾病描述"
              prop="desc"
            >
              <el-input
                v-model="form.desc"
                type="textarea"
                placeholder="请输入疾病信息"
                :autosize="{maxRows:8,minRows:3}"
                :readonly="detailOpen"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item
              label="疾病病因"
              prop="cause"
            >
              <el-input
                v-model="form.cause"
                type="textarea"
                :autosize="{maxRows:8,minRows:3}"
                placeholder="请输入疾病病因"
                :readonly="detailOpen"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item
              label="预防措施"
              prop="prevent"
            >
              <el-input
                v-model="form.prevent"
                type="textarea"
                :autosize="{maxRows:8,minRows:3}"
                placeholder="请输入预防措施信息"
                :readonly="detailOpen"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="宜吃">
              <el-select
                ref="doEat"
                v-model="form.doEat"
                style="width:100%"
                multiple
                filterable
                remote
                allow-create
                default-first-option
                placeholder="请输入食物关键词"
                :remote-method="(query) => { searchInput(query,'food','doEat') }"
                :disabled="detailOpen"
                clearable
                :loading="loading"
                value-key="id"
              >
                <el-option
                  v-for="item in doEat"
                  :key="item.id"
                  :label="item.name"
                  :value="item"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="忌吃">
              <el-select
                ref="noEat"
                v-model="form.noEat"
                style="width:100%"
                multiple
                placeholder="请输入食物关键词"
                :disabled="detailOpen"
                filterable
                remote
                clearable
                allow-create
                default-first-option

                :remote-method="(query) => { searchInput(query,'food','noEat') }"
                :loading="loading"
                value-key="id"
              >
                <el-option
                  v-for="item in noEat"
                  :key="item.id"
                  :label="item.name"
                  :value="item"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="推荐食物">
              <el-select
                ref="recommendEat"
                v-model="form.recommendEat"
                style="width:100%"
                multiple
                placeholder="请输入食物关键词"
                :disabled="detailOpen"
                filterable
                remote
                allow-create
                default-first-option

                clearable
                :remote-method="(query) => { searchInput(query,'food','recommendEat') }"
                :loading="loading"
                value-key="id"
              >
                <el-option
                  v-for="item in recommendEat"
                  :key="item.id"
                  :label="item.name"
                  :value="item"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="推荐药物">
              <el-select
                ref="recommendDrug"
                v-model="form.recommendDrug"
                style="width:100%"
                multiple
                placeholder="请输入药物关键词"
                :disabled="detailOpen"
                filterable
                remote
                allow-create
                default-first-option
                clearable

                :remote-method="(query) => { searchInput(query,'drug','recommendDrug') }"
                :loading="loading"
                value-key="id"
              >
                <el-option
                  v-for="item in recommendDrug"
                  :key="item.id"
                  :label="item.name"
                  :value="item"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="常规用药">
              <el-select
                ref="commonDrug"
                v-model="form.commonDrug"
                style="width:100%"
                multiple
                placeholder="请输入药物关键词"
                :disabled="detailOpen"
                filterable
                remote
                allow-create
                default-first-option
                clearable

                :remote-method="(query) => { searchInput(query,'drug','commonDrug') }"
                :loading="loading"
                value-key="id"
              >
                <el-option
                  v-for="item in commonDrug"
                  :key="item.id"
                  :label="item.name"
                  :value="item"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所需检查">
              <el-select
                ref="needCheck"
                v-model="form.needCheck"
                style="width:100%"
                multiple
                placeholder="请输入所需检查关键词"
                :disabled="detailOpen"
                filterable
                remote
                allow-create
                default-first-option
                clearable

                :remote-method="(query) => { searchInput(query,'check','needCheck') }"
                :loading="loading"
                value-key="id"
              >
                <el-option
                  v-for="item in needCheck"
                  :key="item.id"
                  :label="item.name"
                  :value="item"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="并发症">
              <el-select
                ref="complicationWith"
                v-model="form.complicationWith"
                style="width:100%"
                multiple
                placeholder="请输入所需并发症关键词"
                :disabled="detailOpen"
                filterable
                clearable
                remote
                allow-create
                default-first-option

                :remote-method="(query) => { searchInput(query,'acompany','complicationWith') }"
                :loading="loading"
                value-key="id"
              >
                <el-option
                  v-for="item in complicationWith"
                  :key="item.id"
                  :label="item.name"
                  :value="item"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属科室">
              <el-select
                ref="belongsTo"
                v-model="form.belongsTo"
                style="width:100%"
                multiple
                placeholder="请输入科室关键词"
                :disabled="detailOpen"
                filterable
                remote
                clearable
                allow-create
                default-first-option

                :remote-method="(query) => { searchInput(query,'department','belongsTo') }"
                :loading="loading"
                value-key="id"
              >
                <el-option
                  v-for="item in belongsTo"
                  :key="item.id"
                  :label="item.name"
                  :value="item"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="疾病症状">
              <el-select
                ref="hasSymptom"
                v-model="form.hasSymptom"
                style="width:100%"
                multiple
                placeholder="请输入症状关键词"
                :disabled="detailOpen"
                filterable
                remote
                clearable
                allow-create
                default-first-option

                :remote-method="(query) => { searchInput(query,'symptom','hasSymptom') }"
                :loading="loading"
                value-key="id"
              >
                <el-option
                  v-for="item in hasSymptom"
                  :key="item.id"
                  :label="item.name"
                  :value="item"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import { getToken } from '@/utils/auth'
import {
  addDiseabled,
  delDiseabled,
  getDiseabled,
  listDiseabled,
  updateDiseabled,
  search,
  updateCache
} from '@/api/knowledge/diseabled'
import { cachedOptions, coverStringToObj, parseArray } from '@/utils/sg'
import { Loading, Message } from 'element-ui'
export default {
  name: 'Diseabled',
  data() {
    return {
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined
      },
      title: '',
      open: false,
      detailOpen: false,
      // 表单校验,
      rules: {
      },
      // 显示搜索条件
      showSearch: true,
      // 遮罩层
      loading: true,
      // 用户表格数据
      disabledList: null,
      // 总条数
      total: 0,
      fullscreenLoading: false,
      // 选中数组
      ids: [],
      noEat: [],
      doEat: [],
      recommendEat: [],
      recommendDrug: [],
      commonDrug: [],
      needCheck: [],
      hasSymptom: [],
      complicationWith: [],
      belongsTo: [],
      // 表单参数
      form: {
        id: '',
        name: '',
        desc: '',
        cause: '',
        cureDepartment: '',
        cureWay: '',
        cureLasttime: '',
        curedProb: '',
        easyGet: '',
        getProb: '',
        prevent: '',
        noEat: [],
        doEat: [],
        recommendEat: [],
        recommendDrug: [],
        commonDrug: [],
        needCheck: [],
        hasSymptom: [],
        complicationWith: [],
        belongsTo: []
      }
    }
  },
  watch: {},
  created() {
    this.getList()
  },
  methods: {
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    searchInput(query, type, relation) {
      this.loading = true
      if (query === '' || query === undefined) {
        this.loading = false
        return []
      }
      search({ query: query, type: type, relation: relation }).then(res => {
        this.loading = false
        switch (relation) {
          case 'doEat':
            this.doEat = res
            break
          case 'noEat':
            this.noEat = res
            break
          case 'recommendEat':
            this.recommendEat = res
            break
          case 'recommendDrug':
            this.recommendDrug = res
            break
          case 'commonDrug':
            this.commonDrug = res
            break
          case 'needCheck':
            this.needCheck = res
            break
          case 'complicationWith':
            this.complicationWith = res
            break
          case 'belongsTo':
            this.belongsTo = res
            break
          case 'hasSymptom':
            this.hasSymptom = res
            break
        }
      })
    },
    handleAdd() {
      this.reset()
      this.detailOpen = false
      this.open = true
      this.title = '添加疾病信息'
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    /** 查询用户列表 */
    getList() {
      this.loading = true
      listDiseabled(this.queryParams).then((response) => {
        this.disabledList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    handleDetail(row) {
      this.detailOpen = true
      const id = row.id
      this.getDiseabledById(id, true, '疾病详情')
    },
    getDiseabledById(id, open, title) {
      const loading = this.$loading({
        lock: true,
        text: '拼命加载中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      getDiseabled(id).then((response) => {
        loading.close()
        this.form.id = response.id
        this.form.name = response.name
        this.form.desc = response.desc
        this.form.cause = response.cause
        this.form.cureDepartment = response.cureDepartment
        this.form.cureLasttime = response.cureLasttime
        this.form.cureWay = response.cureWay
        this.form.curedProb = response.curedProb
        this.form.easyGet = response.easyGet
        this.form.getProb = response.getProb
        this.form.prevent = response.prevent
        this.form.doEat = parseArray(response.doEat, 'food')
        this.form.noEat = parseArray(response.noEat, 'food')
        this.form.recommendEat = parseArray(response.recommendEat, 'food')
        this.form.recommendDrug = parseArray(response.recommendDrug, 'drug')
        this.form.commonDrug = parseArray(response.commonDrug, 'drug')
        this.form.needCheck = parseArray(response.needCheck, 'check')
        this.form.complicationWith = parseArray(response.complicationWith, 'acompany')
        this.form.belongsTo = parseArray(response.belongsTo, 'department')
        this.form.hasSymptom = parseArray(response.hasSymptom, 'symptom')
        this.doEat = this.form.doEat
        this.noEat = this.form.noEat
        this.recommendEat = this.form.recommendEat
        this.recommendDrug = this.form.recommendDrug
        this.commonDrug = this.form.commonDrug
        this.needCheck = this.form.needCheck
        this.complicationWith = this.form.complicationWith
        this.belongsTo = this.form.belongsTo
        this.hasSymptom = this.form.hasSymptom
        this.$nextTick(function() {
          cachedOptions(this.$refs.doEat.cachedOptions, this.form.doEat)
          cachedOptions(this.$refs.noEat.cachedOptions, this.form.noEat)
          cachedOptions(this.$refs.recommendEat.cachedOptions, this.form.recommendEat)
          cachedOptions(this.$refs.recommendDrug.cachedOptions, this.form.recommendDrug)
          cachedOptions(this.$refs.commonDrug.cachedOptions, this.form.commonDrug)
          cachedOptions(this.$refs.needCheck.cachedOptions, this.form.needCheck)
          cachedOptions(this.$refs.complicationWith.cachedOptions, this.form.complicationWith)
          cachedOptions(this.$refs.belongsTo.cachedOptions, this.form.belongsTo)
          cachedOptions(this.$refs.hasSymptom.cachedOptions, this.form.hasSymptom)
        })
        this.open = open
        this.title = title
      }).catch(() => {
        loading.close()
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.detailOpen = false
      const id = row.id || this.ids
      this.getDiseabledById(id, true, '修改疾病信息')
    },
    // 表单重置
    reset() {
      this.form = {
        name: undefined,
        desc: undefined,
        cause: undefined,
        cureDepartment: undefined,
        cureLasttime: undefined,
        cureWay: undefined,
        curedProb: undefined,
        easyGet: undefined,
        getProb: undefined,
        prevent: undefined,
        noEat: undefined,
        doEat: undefined,
        recommendEat: undefined,
        recommendDrug: undefined,
        commonDrug: undefined,
        needCheck: undefined,
        hasSymptom: undefined,
        complicationWith: undefined,
        belongsTo: undefined
      }
      this.noEat = []
      this.doEat = []
      this.recommendEat = []
      this.recommendDrug = []
      this.commonDrug = []
      this.needCheck = []
      this.hasSymptom = []
      this.complicationWith = []
      this.belongsTo = []
      this.resetForm('form')
    },
    handleUpdateCachedisabled() {
      const loadingInstance = Loading.service({
        lock: true,
        text: '正在更新ing',
        spinner: 'el-icon-loading',
        background: 'rgba(0,0,0,0.7)'
      })
      updateCache().then(response => {
        this.$nextTick(() => { // 以服务的方式调用的 Loading 需要异步关闭
          setTimeout(function() {
            loadingInstance.close()
            Message.success('操作成功')
          }, 500)
        })
      }).catch(() => {
        loadingInstance.close()
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal
        .confirm('是否确认删除编号为"' + ids + '"的数据项？')
        .then(function() {
          return delDiseabled(ids)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
    },
    /** 提交按钮 */
    submitForm() {
      if (this.detailOpen) {
        this.open = false
        return
      }
      this.$refs['form'].validate((valid, error) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '正在执行中......',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          this.form.doEat = coverStringToObj(this.form.doEat)
          this.form.noEat = coverStringToObj(this.form.noEat)
          this.form.recommendEat = coverStringToObj(this.form.recommendEat)
          this.form.recommendDrug = coverStringToObj(this.form.recommendDrug)
          this.form.commonDrug = coverStringToObj(this.form.commonDrug)
          this.form.needCheck = coverStringToObj(this.form.needCheck)
          this.form.complicationWith = coverStringToObj(this.form.complicationWith)
          this.form.belongsTo = coverStringToObj(this.form.belongsTo)
          this.form.hasSymptom = coverStringToObj(this.form.hasSymptom)
          if (this.form.id !== undefined) {
            updateDiseabled(this.form).then((response) => {
              loading.close()
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            }).catch(() => {
              loading.close()
            })
          } else {
            addDiseabled(this.form).then((response) => {
              this.$modal.msgSuccess('新增成功')
              loading.close()
              this.open = false
              this.getList()
            }).catch(() => {
              loading.close()
            })
          }
        } else {
          return
        }
      })
    }
  }
}
</script>
